<template>
	<!-- 应急救援 -->
	<CustomNavbar></CustomNavbar>
	<view class="rescue-page">
		<view class="test">应急救援</view>
		<!-- 顶部地图占位与地址气泡 -->
		<view class="map-card">
			<!-- 			<view class="map-placeholder">
				<view class="addr-bubble">{{ formState.address || '山阳区人民西路32号' }}</view>
			</view> -->

			<!-- 地图 -->
			<view class="dtmk">
				<map 
					class="dt" 
					name="" 
					:latitude="latitude" 
					:longitude="longitude"
					:markers="mapMarkers"
					:scale="mapScale"
					show-location
					:show-compass="true"
					:enable-zoom="true"
					:enable-scroll="true">
				</map>
				<!-- 定位按钮 -->
				<view class="location-btn" @click="refreshLocation">
					<image src="/static/index/定位2@2x.png" class="location-icon" mode="aspectFit"></image>
				</view>
			</view>

		</view>

		<!-- 选项卡 -->
		<view class="tabs">
			<view v-for="(tab, idx) in tabs" :key="tab" :class="['tab-item', currentTab === idx ? 'active' : '']"
				@click="switchTab(idx)">
				{{ tab }}
			</view>
		</view>

		<!-- 表单区域：根据选项不同切换内容 -->
		<view class="form-card">
			<template v-if="currentTab === 2">
				<!-- 拖车：起点/终点 -->
				<view class="form-row">
					<view class="label">起点</view>
					<input class="value" v-model="formState.towStart" placeholder="河南省焦作市山阳区32号" />
				</view>
				<view class="form-row">
					<view class="label">终点</view>
					<input class="value" v-model="formState.towEnd" placeholder="请输入终点" />
				</view>
			</template>
			<template v-else>
				<!-- 搭电/换胎：位置 -->
				<view class="form-row">
					<view class="label">位置</view>
					<input class="value" v-model="formState.address" placeholder="河南省焦作市山阳区32号" />
				</view>
			</template>

			<view class="form-row">
				<view class="label">求助人</view>
				<input class="value" v-model="formState.contactName" placeholder="张先生" />
			</view>
			<view class="form-row">
				<view class="label">联系方式</view>
				<input class="value" v-model="formState.contactPhone" placeholder="15523632541" />
			</view>
			<view class="form-row">
				<view class="label">车牌</view>
				<input class="value" v-model="formState.plate" placeholder="豫CJ4321" />
			</view>
			<view class="form-row text">
				<view class="label">描述</view>
				<textarea class="value textarea" v-model="formState.desc" placeholder="请准确描述当前的状况及所需的帮助" />
			</view>

			<button class="primary-btn" @click="submit">呼叫救援</button>
			<view class="record-link" @click="openRecord">救援记录</view>
		</view>

		<!-- 警务救助区块（静态展示） -->
		<view class="police-card">
			<view class="police-title">警务救助</view>
			<view class="police-list">
				<view class="police-item">
					<image src="/static/Rescue/交通事故 拷贝.png" mode="" class="img"></image>
					<view class=" p-name">交通事故
					</view>
					<view class="p-num">122</view>
				</view>
				<view class="police-item">
					<image src="/static/Rescue/火警.png" mode="" class="img"></image>
					<view class=" p-name">火警
					</view>
					<view class="p-num">119</view>

				</view>
				<view class="police-item">
					<image src="/static/Rescue/急救包.png" mode="" class="img"></image>
					<view class=" p-name">急救中心
					</view>
					<view class="p-num">120</view>

				</view>
				<view class="police-item">
					<image src="/static/Rescue/警察,公安.png" mode="" class="img"></image>
					<view class="p-name">公安报警</view>
					<view class="p-num">110</view>
				</view>
			</view>
		</view>

		<!-- 自定义底部导航 -->
		<CustomTabbar active="rescue" />
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue'
	import CustomTabbar from '@/components/CustomTabbar.vue'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import { getLocation } from '@/utils/location.js'
	
	// 从存储中获取位置信息
	const getLocationFromStorage = () => {
		return getLocation()
	}
	
	const tabs = ['搭电', '换胎', '拖车']
	const currentTab = ref(0)

	// 经纬度
	const latitude = ref(34.825817)
	const longitude = ref(113.55852)
	const mapScale = ref(16)
	
	// 地图标记点
	const mapMarkers = ref([])
	// 更新地图标记点
	const updateMapMarkers = () => {
		mapMarkers.value = [{
			id: 1,
			latitude: latitude.value,
			longitude: longitude.value,
			iconPath: '/static/index/定位2@2x.png',
			width: 32,
			height: 32,
			anchor: { x: 0.5, y: 0.5 },
			title: '我的位置'
		}]
	}
	
	//app实时定位
	const getPosition = () => {
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				console.log(res)
				console.log('当前位置的经度：', res.longitude)
				console.log('当前位置的纬度：', res.latitude)
				longitude.value = res.longitude;
				latitude.value = res.latitude;
				// 更新地图标记点
				updateMapMarkers()
				// 获取位置后，进行逆地理编码获取地址
				reverseGeocodeForForm(res.latitude, res.longitude)
			},
			fail: function(err) {
				console.error('定位失败：', err);
				uni.showToast({
					title: '定位失败，请检查定位权限',
					icon: 'none'
				})
			}
		})
	}
	
	// 刷新定位
	const refreshLocation = () => {
		uni.showLoading({
			title: '定位中...'
		})
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				console.log(res)
				console.log('当前位置的经度：', res.longitude)
				console.log('当前位置的纬度：', res.latitude)
				longitude.value = res.longitude;
				latitude.value = res.latitude;
				// 更新地图标记点
				updateMapMarkers()
				// 获取位置后，进行逆地理编码获取地址
				reverseGeocodeForForm(res.latitude, res.longitude)
				uni.hideLoading()
				uni.showToast({
					title: '定位成功',
					icon: 'success',
					duration: 1500
				})
			},
			fail: function(err) {
				uni.hideLoading()
				console.error('定位失败：', err);
				uni.showToast({
					title: '定位失败，请检查定位权限',
					icon: 'none'
				})
			}
		})
	}
	
	// 逆地理编码（用于填充表单地址）
	const reverseGeocodeForForm = (latitude, longitude) => {
		const key = 'EJABZ-ZBULT-UFMXD-VT6JM-I37RS-OZFVN'
		const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=1`

		uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data.status === 0) {
					const result = res.data.result
					// 填充地址到表单
					if (result.address) {
						formState.address = result.address
						formState.towStart = result.address
					} else if (result.address_component?.city) {
						formState.address = result.address_component.city
						formState.towStart = result.address_component.city
					}
				}
			},
			fail: (err) => {
				console.error('逆地理编码失败：', err)
			}
		})
	}
	// 获取位置（返回Promise）
	const getPositionOnce = () => {
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'wgs84',
				success: function(res) {
					console.log(res)
					console.log('当前位置的经度：', res.longitude)
					console.log('当前位置的纬度：', res.latitude)
					longitude.value = res.longitude;
					latitude.value = res.latitude;
					resolve(res);
				},
				fail: function(err) {
					console.error('定位失败：', err);
					reject(err);
				}
			})
		})
	}
	//获取地址
	const choose = () => {
		// #ifdef H5
		navigator.geolocation.getCurrentPosition(
			position => {
				console.log(position.coords.latitude, position.coords.longitude);
				// 处理获取到的位置信息
				uni.chooseLocation({
					success(resp) {
						console.log(resp);
					}
				})
			},
			error => {
				console.error(error);
				// 处理错误
			}
		);
		// #endif
		// #ifndef H5
		uni.chooseLocation({
			success(resp) {
				console.log(resp);
			},
			fail(err) {
				console.error('选择位置失败：', err);
			}
		})
		// #endif
	}
	// 当页面加载后立马执行
	onLoad(() => {
		// 优先从存储中获取位置信息
		const savedLocation = getLocationFromStorage()
		if (savedLocation) {
			latitude.value = savedLocation.latitude
			longitude.value = savedLocation.longitude
			// 更新地图标记点
			updateMapMarkers()
			// 填充位置信息到表单
			if (savedLocation.address) {
				formState.address = savedLocation.address
				formState.towStart = savedLocation.address
			} else if (savedLocation.city) {
				formState.address = savedLocation.city
				formState.towStart = savedLocation.city
			}
		} else {
			// 如果没有存储的位置，则获取当前位置
			getPosition()
		}
		
		// 监听位置更新事件
		uni.$on('locationUpdated', (locationData) => {
			if (locationData) {
				latitude.value = locationData.latitude
				longitude.value = locationData.longitude
				// 更新地图标记点
				updateMapMarkers()
				// 更新表单中的位置信息
				if (locationData.address) {
					formState.address = locationData.address
					formState.towStart = locationData.address
				} else if (locationData.city) {
					formState.address = locationData.city
					formState.towStart = locationData.city
				}
			}
		})
	})

	// 页面卸载时清理定位监听
	onUnload(() => {
		try {
			// #ifdef H5
			if (h5WatchId !== null && navigator.geolocation?.clearWatch) {
				navigator.geolocation.clearWatch(h5WatchId)
				h5WatchId = null
			}
			// #endif
			// #ifndef H5
			uni.offLocationChange && uni.offLocationChange()
			uni.stopLocationUpdate && uni.stopLocationUpdate()
			// #endif
			// 移除事件监听
			uni.$off('locationUpdated')
		} catch (e) {
			console.error('清理定位监听失败：', e);
		}
	})

	const formState = reactive({
		address: '',
		contactName: '',
		contactPhone: '',
		plate: '',
		desc: '',
		// 拖车
		towStart: '',
		towEnd: ''
	})

	function switchTab(idx) {
		currentTab.value = idx
	}

	function submit() {
		const type = tabs[currentTab.value]
		uni.showToast({
			title: `${type} 请求已提交`,
			icon: 'success'
		})
	}

	function openRecord() {
		// 获取当前选中的救援类型
		const currentType = tabs[currentTab.value]
		uni.navigateTo({
			url: `/pages/Rescue/RescueList/RescueList?type=${currentType}`,
			fail: () => {
				uni.showToast({
					title: '页面未找到',
					icon: 'none'
				})
			}
		})
	}
</script>

<style>
	.test {
		color: white;
		font-size: 35rpx;
		text-align: center;
		margin-bottom: 40rpx;
	}

	.rescue-page {
		position: relative;
		top: -390rpx;
		padding: 16rpx 24rpx 48rpx;
	}

	.map-card {
		background: #ffffff;
		border-radius: 24rpx;
		padding: 16rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.04);
	}

	.map-placeholder {
		height: 420rpx;
		background: #f2f5ff;
		border-radius: 16rpx;
		position: relative;
	}

	.addr-bubble {
		position: absolute;
		right: 24rpx;
		top: 24rpx;
		background: #ffffff;
		border-radius: 999rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
		color: #333;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
	}

	.tabs {
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-top: 32rpx;
		background: #ffffff;
		border-radius: 24rpx;
		padding: 16rpx;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 24rpx 0;
		font-size: 32rpx;
		color: #333;
		border-bottom: 4rpx solid transparent;
	}

	.tab-item.active {
		color: #0a84ff;
		font-weight: 600;
		border-bottom-color: #0a84ff;
	}

	.img {
		width: 45rpx;
		height: 45rpx;
	}

	.form-card {
		margin-top: 24rpx;
		background: #ffffff;
		border-radius: 24rpx;
		padding: 24rpx;
	}

	.form-row {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.form-row.text {
		align-items: flex-start;
	}

	.label {
		width: 140rpx;
		background: #3c9cff;
		color: #fff;
		border-radius: 999rpx;
		text-align: center;
		padding: 16rpx 0;
		margin-right: 16rpx;
		font-size: 28rpx;
	}

	.value {
		flex: 1;
		background: #f7f8fa;
		border-radius: 999rpx;
		padding: 20rpx 28rpx;
		font-size: 28rpx;
	}

	.textarea {
		min-height: 180rpx;
		border-radius: 16rpx;
	}

	.primary-btn {
		margin-top: 24rpx;
		background: linear-gradient(90deg, #ff7a2f, #ff4d2f);
		color: #fff;
		border-radius: 999rpx;
		height: 96rpx;
		line-height: 96rpx;
		font-size: 32rpx;
	}

	.record-link {
		text-align: center;
		color: #888;
		margin-top: 16rpx;
	}

	.police-card {
		margin-top: 24rpx;
		background: #ffffff;
		border-radius: 24rpx;
		padding: 24rpx;
		margin-bottom: 94rpx;
	}

	.police-title {
		font-size: 32rpx;
		color: #111;
		margin-bottom: 12rpx;
	}

	.police-list {
		display: flex;
		justify-content: space-between;
	}

	.police-item {
		width: 24%;
		background: #f7f8fa;
		border-radius: 16rpx;
		padding: 24rpx 0;
		text-align: center;
	}

	.p-name {
		color: #333;
		font-size: 26rpx;
	}

	.p-num {
		color: #888;
		font-size: 26rpx;
		margin-top: 8rpx;
		font-style: italic;
	}

	/* 地图模块 */
	.dtmk {
		background-color: white;
		position: relative;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.dt {
		width: 670rpx;
		height: 350rpx;
	}
	
	/* 定位按钮 */
	.location-btn {
		position: absolute;
		right: 20rpx;
		bottom: 20rpx;
		width: 80rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		z-index: 10;
	}
	
	.location-icon {
		width: 40rpx;
		height: 40rpx;
	}
</style>